package com.wangsd.system.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wangsd.common.controller.AjaxResult;
import com.wangsd.common.controller.BaseController;
import com.wangsd.common.exception.BusinessErrorEnum;
import com.wangsd.common.exception.BusinessException;
import com.wangsd.common.jwt.LoginUser;
import com.wangsd.common.jwt.PassToken;
import com.wangsd.common.jwt.TokenService;
import com.wangsd.common.utils.ServletUtils;
import com.wangsd.system.entity.SysRole;
import com.wangsd.system.entity.SysUser;
import com.wangsd.system.service.SysRoleService;
import com.wangsd.system.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户Controller
 *
 * @author wsd
 * @date 2021-03-16
 */
@Api(tags = "用户管理")
@RestController
@RequestMapping("/system/user")
public class SysUserController extends BaseController {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private SysRoleService roleService;

    @ApiOperation(value = "查询用户列表")
    @GetMapping("/list")
    public AjaxResult<PageInfo<SysUser>> list(SysUser sysUser) {
        if (sysUser.getUserType() == null) {
            throw new BusinessException(BusinessErrorEnum.PARAMETER_VALIDATION_ERROR, "userType不能为空");
        }

        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());

        Page page = PageHelper.startPage(ServletUtils.getParameterToInt("pageNum"), ServletUtils.getParameterToInt("pageSize"));
        List<SysUser> list = sysUserService.selectSysUserList(sysUser, loginUser.getSysUser().getParentCode());
        return AjaxResult.success(getPageInfo(page, list));
    }


    @ApiOperation(value = "获取用户详细信息")
    @GetMapping("/{id}")
    public AjaxResult<SysUser> getInfo(@PathVariable("id") Long id) {
        SysUser sysUser = sysUserService.selectSysUserById(id);
        List<SysRole> roleList = roleService.selectRoleByUserId(sysUser.getId());
        List<Long> roles = roleList.stream().map(SysRole::getId).collect(Collectors.toList());
        sysUser.setRoleIds(roles);
        return AjaxResult.success(sysUser);
    }

    @ApiOperation(value = "新增/修改用户")
    @PostMapping("/saveOrUpdate")
    public AjaxResult saveOrUpdate(@RequestBody SysUser sysUser) {
        SysUser entity = sysUserService.checkName(sysUser.getUsername(), sysUser.getId());
        if (entity != null) {
            throw new BusinessException(BusinessErrorEnum.UNKNOWN_ERROR, "名称不能重复");
        }
        if (sysUser.getUserType() == null) {
            throw new BusinessException(BusinessErrorEnum.PARAMETER_VALIDATION_ERROR, "userType不能为空");
        }
        if (sysUser.getId() == null){
            sysUserService.insertSysUser(sysUser);
        } else {
            sysUserService.updateSysUser(sysUser);
        }
        return AjaxResult.success("success");
    }


    @ApiOperation(value = "删除用户")
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable Long id) {
        sysUserService.deleteSysUserById(id);
        return AjaxResult.success("success");
    }

    @PassToken
    @ApiOperation(value = "登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "登陆账号", required = true),
            @ApiImplicitParam(name = "password", value = "密码", required = true)
    })
    @PostMapping("/userLogin")
    public AjaxResult userLogin(String username, String password) {
        SysUser user = sysUserService.userLogin(username, password);
        LoginUser loginUser = LoginUser.builder().sysUser(user).build();
        String token = tokenService.createToken(loginUser);
        return AjaxResult.success(token);
    }

    @ApiOperation(value = "退出登录")
    @PostMapping("/logout")
    @PassToken
    public AjaxResult logout() {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        if (loginUser != null) {
            tokenService.delLoginUser(loginUser.getToken());
        }
        return AjaxResult.success("success");
    }

    @ApiOperation(value = "修改密码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "oldPass", value = "旧密码", required = true),
            @ApiImplicitParam(name = "password", value = "新密码", required = true)
    })
    @PutMapping("/updatePassword")
    public AjaxResult updatePassword(String oldPass, String password) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser user = loginUser.getSysUser();
        if (!user.getPassword().equals(oldPass)) {
            throw new BusinessException(BusinessErrorEnum.PARAMETER_VALIDATION_ERROR, "输入的旧密码不对");
        }
        user.setPassword(password);
        sysUserService.updateSysUser(user);
        return AjaxResult.success("success");
    }

    @ApiOperation(value = "获取登录用户权限（拥有哪些菜单）")
    @GetMapping("/selectPermission")
    public AjaxResult<SysUser> selectPermission() {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser user = loginUser.getSysUser();
        user = sysUserService.selectPermission(user);
        return AjaxResult.success(user);
    }

    @ApiOperation(value = "启用 禁用")
    @PutMapping("/status/{id}")
    public AjaxResult status(@PathVariable Long id) {
        sysUserService.changeStatus(id);
        return AjaxResult.success("success");
    }
}
